<template>
  <el-dialog
    title="填写导出的文件名"
    :model-value="props.modelValue"
    width="30%"
    @close="closed"
  >
    <el-input placeholder="请输入导出的文件名" v-model="fileNmae"></el-input>
    <template #footer>
      <div>
        <el-button @click="closed">取消</el-button>
        <el-button type="primary" :loading="loading" @click="onConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue'
import { userAllList } from '@/api/user-manage'
import { USER_RELATIONS } from './utils'
import { dateFilter } from '@/filters'
const DEFAULT_FILENAME = '所有员工列表'
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})
const emits = defineEmits(['update:modelValue'])
const fileNmae = ref(DEFAULT_FILENAME)
const loading = ref(false)

const onConfirm = async () => {
  loading.value = true
  const { list } = await userAllList()
  // 异步导入Export2Excel通用组件
  const { export_json_to_excel: exportJsonToExcel } = await import('@/utils/Export2Excel')
  exportJsonToExcel({
    header: Object.keys(USER_RELATIONS), // 设置表头
    data: formatJson(USER_RELATIONS, list), // 设置表内容
    filename: fileNmae.value // 设置文件名
  })
  console.log(list)
  console.log(formatJson(USER_RELATIONS, list))
  loading.value = false
  closed()
}

const closed = () => {
  emits('update:modelValue', false)
}

/**
 * 格式化json数据，将json数据转化为ecxcel可以识别的二维数组
 */
const formatJson = (headers, rows) => {
  return rows.map(row => {
    const list = []
    Object.entries(headers).map(([key, value]) => {
      if (value === 'role') {
        const roleSting = JSON.stringify(row[value].map(item => item.title))
        list.push(roleSting)
      } else if (value === 'openTime') {
        list.push(dateFilter(row[value]))
      } else {
        list.push(row[value])
      }
    })
    return list
  })
}
</script>

<style>
</style>
